package com.project.fiveCerealsSavoury.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitterReturnValueHandler;

import com.project.fiveCerealsSavoury.domain.Goods;
import com.project.fiveCerealsSavoury.domain.User;
import com.project.fiveCerealsSavoury.exception.BizException;
import com.project.fiveCerealsSavoury.service.GoodsService;
import com.project.fiveCerealsSavoury.transfer.GoodsNew;

import com.project.fiveCerealsSavoury.transfer.Page;
import com.project.fiveCerealsSavoury.transfer.UserLogin;
import com.project.fiveCerealsSavoury.transfer.UserPage;
import com.sun.org.apache.bcel.internal.generic.NEW;
/**
 * 添加商品
 * @author Administrator
 *
 */
import com.sun.org.apache.xml.internal.resolver.helpers.PublicId;
@Controller
public class GoodsController {
	@Autowired
	GoodsService goodsService;
	
	@RequestMapping(value="/upload.htm",method=RequestMethod.GET)
	public String insert(@ModelAttribute("goods") Goods goods1){
		return "/admin/addGood";
	}
	
	@RequestMapping(value ="/upload.do",method=RequestMethod.POST)
	public String upload(@RequestParam(value="file",required=false) MultipartFile file, @Valid @ModelAttribute("goods")Goods goods1,HttpServletRequest request,BindingResult result){
		if(result.hasErrors()){
			return "/admin/addGood";
		}
		if(file.isEmpty() || file == null){
			return "/admin/add-good";
		}
		//设置存放的文件名以及目录
		int lastIndexof = file.getOriginalFilename().lastIndexOf(".");
		String oriFileNameSuffix = lastIndexof != -1 ? file.getOriginalFilename().substring(lastIndexof):"";
		//后缀集
		List<String> suffixs = Arrays.asList(".png",".jpg",".jpeg",".gif");
		if(!suffixs.contains(oriFileNameSuffix)){
			//识别
			return "/admin/add-good";
		}
		String destFileName = UUID.randomUUID()+oriFileNameSuffix;
		String destFilePath = request.getSession().getServletContext().getRealPath("/")+"/upload/";
		File destFile = new File(destFilePath,destFileName);
		if(!destFile.getParentFile().exists())destFile.mkdir();//如果没有这个目录就创建
		// 转存到服务器本地目录
		String url = "../dt/upload/"+destFile.getName();
		try {
			file.transferTo(destFile);
			request.setAttribute("url", url);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
			// 重定向
			return "redirect:/upload.htm";
		}
		try {
			if(destFileName != null){
				goods1.setUrl(url);
				goodsService.add(goods1);
				
			}
			return "forward:/que.do?boo=true";
		} catch (Exception e) {
			e.printStackTrace();
			// 重定向
			return "redirect:/upload.htm";
		}
		
	}
	/**
	 * 修改商品
	 * @param goodsNew
	 * @return
	 */
	@RequestMapping(value="/amend.htm")
	public String loginPage(@ModelAttribute("goods")GoodsNew goodsNew,HttpServletRequest request,ModelMap modelMap){
		try {
			Goods goods = goodsService.query(goodsNew.getId());
			modelMap.put("goods", goods);
			
		} catch (Exception e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
		
 		return "/good/amendGoods";	
	}
	@RequestMapping(value ="/amend.do",method=RequestMethod.POST)
	public String modify(@Valid  @ModelAttribute("goods")GoodsNew goodsNew,HttpServletRequest request,ModelMap modelMap){
		try {
			
			if(goodsNew != null){
				goodsService.amend(goodsNew.getId(), goodsNew.getGoodName(), goodsNew.getPrice(), goodsNew.getNowPrice(), goodsNew.getCount(), goodsNew.getWeight());
				modelMap.put("message", "alert('修改成功')");
				return "/good/amendGoods";
			};
		} catch (Exception e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "/good/amendGoods";
	}
	@RequestMapping(value ="/delete.do")
	public String del(Integer id){
		try {
			Goods goods2 = goodsService.query(id);
			if(goods2 != null){
				goodsService.remove(id);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "redirect:/list.do";
	}
	
	@RequestMapping(value="/good/single.do")
	public String single(ModelMap modelMap,@RequestParam(value="id",required=false) Integer id) throws BizException{
		List<Goods> good1=new ArrayList<>();
		Goods query = goodsService.query(id);
		String urls = query.getUrl();
		String splits = urls.replaceAll("/dt","");
		query.setUrl(splits);
		good1.add(query);
		modelMap.put("goods", good1);
		
		List<Goods> good2=null;
		List<Goods> good3=null;
		List<Goods> que = goodsService.que();
		int i = 0;
		for(Goods goods : que){
			if (!goods.getUrl().contains("center")) {
				String url = goods.getUrl();
				System.err.println("===="+url);
				String split = url.replaceAll("/dt","");
				System.err.println("===="+split);
				goods.setUrl(split);
				if(i<3){
					if(good2 == null){
						good2=new ArrayList<>();
					}
					good2.add(goods);
					modelMap.put("goods1", good2);
				}else if(i>=3 && i<7){
					if(good3 == null){
						good3=new ArrayList<>();
					}
					good3.add(goods);
					modelMap.put("goods2", good3);
				}
				i++;
			}
		}
		return "/good/single";
	}
	
	@RequestMapping(value ="/que.do")
	public String queryss(ModelMap map,boolean boo) throws BizException{
		List<Goods> queryAll = goodsService.que();
		map.put("shopping", queryAll);
		if (boo) {
			return "/admin/warehouse";
		}
		tmp(queryAll, map);
		return "/shopping";
	}
	
	@RequestMapping(value ="/queryGoodName.do")
	public String queryGoodName(String goodName,ModelMap map) throws BizException{
		if (goodName == null)throw new  BizException("货物名称不能为空");
		List<Goods> que = goodsService.que();
		List<Goods> goods2 = new ArrayList<>();
		for(int i = 0;i < que.size() ;i++){
			Goods goods3 = que.get(i);
			if (goods3.getUrl().contains("center")) {
				goods2.add(goods3);
			}
		}
		map.put("shop1", goods2);
		List<Goods> goodss = new ArrayList<>();
		List<Goods> queryAll = goodsService.queryAll(goodName);
		for (Goods goods : queryAll) {
			if (!goods.getUrl().contains("center")) {
				goodss.add(goods);
			}
		}
		map.put("shop2", goodss);
		tmp(queryAll, map);
		return "/shopping";
	}
	
	@RequestMapping(value="/list.do")
	public String queryPage(@Valid UserPage userPage,ModelMap map){
		Page  lists = goodsService.list(userPage);
		if(lists == null){
			return "";
		} 
		map.put("lists", lists);
		return "/admin/list-good";
		
	}
	
	public void tmp(List<Goods> queryAll,ModelMap map){
		List<Goods> goods2 = null;
		List<Goods> goods4 = null;
		List<Goods> goods5 = null;
		for(int i = 0;i < queryAll.size() ;i++){
			Goods goods3 = queryAll.get(i);
			if (goods3.getCount() > 0) {
				if (i < 5) {
					if(goods2 == null){
						goods2 = new ArrayList<>();
					}
					goods2.add(goods3);
					map.put("shop1", goods2);
				}else if (i>=5 &&i < 10) {
					if(goods4 == null){
						goods4 = new ArrayList<>();
					}
					goods4.add(goods3);
					map.put("shop", goods4);
				}else {
					if(goods5 == null){
						goods5 = new ArrayList<>();
					}
					goods5.add(goods3);
					map.put("shop2", goods5);
				}
			}
		}
	}
}
